<template>
  <div style="height: 100%;">
    <a-row :class="['p-4', `${prefixCls}--box`]" type="flex" :gutter="10" style="height: 100%;">
      <a-col :xl="6" :lg="24" :md="24" style="margin-bottom: 10px">
        <BasicTree title="选择模板" :treeData="treeDataBase" @select="onTreeSelect" :fieldNames="{ title: 'templateName', key: 'id' }" />
      </a-col>
      <a-col :xl="18" :lg="24" :md="24" style="margin-bottom: 10px">
        <div style="height: 100%;" :class="[`${prefixCls}`]">
          <!--引用表格-->
          <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox', columnWidth: 30, selectedRowKeys: checkedKeys, onChange: onSelectChange, onSelectAll: onSelectNone, onSelect: onSelect, }">
            <template #bodyCell="{ column, text, record }">
              <!-- 指标名称 -->
              <template v-if="column.editRow && column.dataIndex === 'indexName'">
                <a-input v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
              </template>
              <!-- 权重 -->
              <template v-if="column.editRow && column.dataIndex === 'factorWeight'">
                <a-input-number v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" addon-after="%" :min="0" />
              </template>
              <!-- 考核周期 -->
              <template v-if="column.editRow && column.dataIndex === 'periodCode'">
                <a-select v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" :options="periodTree" allow-clear :fieldNames="{ label: 'periodName', value: 'periodCode' }" />
                <!-- <a-input-number v-if="startEdit && record.editId || record.isAdd" v-model:value="record[column['dataIndex']]"/> -->
              </template>
              <!-- 指标内容 -->
              <template v-if="column.editRow && column.dataIndex === 'indexTxt'">
                <a-input v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
              </template>
              <!-- 评价依据 -->
              <template v-if="column.editRow && column.dataIndex === 'evaluateGist'">
                <a-input v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
              </template>
              <!-- 评价标准 -->
              <template v-if="column.editRow && column.dataIndex === 'evaluateCriterion'">
                <a-input v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
              </template>
              <!-- 排序 -->
              <template v-if="column.editRow && column.dataIndex === 'displayOrder'">
                <a-input-number v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
              </template>
              <!-- 动态表头 -->
              <template v-if="column.dataIndex && column.dataIndex.includes('elementScore')">
                <a-input v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
              </template>
            </template>
            <!--插槽:table标题-->
            <template #tableTitle>
              <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd">新增</a-button>
              <a-button type="primary" @click="handleEdit" v-if="!startEdit">批量编辑</a-button>
              <a-button type="primary" v-if="startEdit" @click="handleSave">保存</a-button>
              <!-- <a-button type="primary" v-if="!startEdit" @click="toTemplateConfig">模板配置</a-button> -->
              <a-button v-if="startEdit" @click="editCancel">取消</a-button>
            </template>
            <!--操作栏-->
            <template #action="{ record, index }">
              <TableAction :actions="getTableAction(record, index)" />
            </template>
          </BasicTable>
        </div>
      </a-col>
    </a-row>

    <!-- 表单区域 -->
    <HubTeamTemplateConfigModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="emp-team-index-HubTeamEvaluateIndex" setup>
import { ref, onMounted, provide, reactive, computed, unref, nextTick } from 'vue';
import { PageWrapper } from '/@/components/Page';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { BasicTree, ContextMenuItem } from '/@/components/Tree/index';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage';
import HubTeamTemplateConfigModal from './components/HubTeamEvaluateIndexModal.vue';
import { columns, searchFormSchema } from './HubTeamEvaluateIndex.data';
import { pageList, deleteOne, batchDelete, getImportUrl, getExportUrl, treeList, getTemplateConfigHeader, updateList, saveOrUpdate, } from './HubTeamEvaluateIndex.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message } = useMessage(); // 解构
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

import { useDesign } from '/@/hooks/web/useDesign';
const { prefixCls } = useDesign('depart-manage');
provide('prefixCls', prefixCls);

const checkedKeys = ref<Array<string | number>>([]);
const startEdit = ref(false);
const startAdd = ref(false);
const showActionColumn = ref(true);
// 树形控件
const selectedKeys = ref([]);
const treeDataBase = ref([]);
//注册model
const [registerModal, { openModal }] = useModal();
//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: 'hub_team_evaluate_index',
    api: pageList,
    columns,
    canResize: false,
    // dataSource: mockDate,
    showIndexColumn: true,
    showActionColumn: showActionColumn,
    rowKey: 'id',
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    }, //表格和查询条件同步更新的方法
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    immediate: false,
  },
  exportConfig: {
    name: 'hub_team_template_config',
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess,
  },
});

const [registerTable, { getForm, reload, getDataSource, getColumns, setColumns, setTableData }, { rowSelection, selectedRowKeys }] = tableContext;

//页面公共参数
const queryParam = reactive<any>({});

// 默认执行一次
const orgName = ref(userStore.getOrgName);
onMounted(async () => {
  initTree();
  let form = getForm();
  form.updateSchema([
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e, i) => {
          setTableData([]);
          orgName.value = i?.label;
          initTree(e);
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
});

/**
 * 初始化树
 */
async function initTree(orgCode?) {
  // debugger
  orgCode = orgCode ? orgCode : getForm().getFieldsValue().orgCode;
  let res = await treeList({ orgCode: orgCode });
  treeDataBase.value = res;
}

/**
 * 新增事件
 */
function handleAdd() {
  if (!queryParam.templateId) {
    $message.error('请选择左侧模板');
    return;
  }
  startAdd.value = true;
  startEdit.value = true; // 显示保存按钮
  showActionColumn.value = false; // 显示操作栏按钮
  const data = getDataSource();
  data.unshift({
    // isAdd: true,
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  if (!queryParam.templateId) {
    $message.error('请选择左侧模板');
    return;
  }
  startEdit.value = true;
}
/**
 * 详情
 */
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record, index) {
  console.log('111', index);
  let tableData = getDataSource();
  if (!record.id) {
    tableData.splice(index, 1);
    console.log('tableData', tableData);
    setTableData(tableData);
  } else {
    await deleteOne({ id: record.id }, handleSuccess);
  }
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
 * 操作栏
 */
function getTableAction(record, index) {
  return [
    //  {
    //    label: '编辑',
    //    onClick: handleEdit.bind(null, record),
    //  },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record, index),
      },
    },
  ];
}
/**
 * 下拉操作栏
 */
function getDropDownAction(record, index) {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record, index),
      },
    },
  ];
}

// 树点击回调
async function onTreeSelect(k, { selected, selectedNodes, node, event }) {
  queryParam.templateId = selected ? k[0] : null;
  queryParam.templateCode = selected ? selectedNodes[0].templateCode : null;
  handleSuccess();
  let params = {
    orgCode: node.orgCode,
    type: node.type
  }
  // 获取动态表头
  let res = await getTemplateConfigHeader(params);
  let newColumn = getColumns();
  res.forEach((item) => {
    let temp: any = {
      title: item.headName,
      dataIndex: item.headCode,
      width: 200,
      align: 'center',
    };
    newColumn.splice(newColumn.length - 2, 0, {
      ...temp,
    });
  });
  setColumns(newColumn);
}


const getTableColumn = async (params) => {
  setColumns(columns);
  let newColumn = getColumns();
  getTemplateConfigHeader(params).then((res) => {

    nextTick(() => {
      setColumns(newColumn);
    });
  });
};

/**
 * 选择事件
 */
function onSelectChange(selectedRowKeys: (string | number)[], selectedRows) {
  checkedKeys.value = selectedRowKeys;
  selectedRows.forEach((item) => {
    item.editId = selectedRowKeys;
  });
  console.log(selectedRows);
  console.log(checkedKeys.value);
  if (checkedKeys.value.length === 0) {
    startEdit.value = false;
    onSelectNone();
  }
}

// 用户手动选择/取消选择所有列的回调
function onSelectNone() {
  let records = getDataSource();
  records.forEach((item) => {
    delete item.editId;
  });
  let newRecords = unref(records.filter((item) => item.indexCode));
  setTableData(newRecords);
}

// 用户手动选择/取消选择某列的回调
function onSelect(record, selected) {
  if (selected === false) {
    delete record.editId;
  }
}

// 取消回调
async function editCancel() {
  checkedKeys.value = [];
  startEdit.value = false;
  showActionColumn.value = true;
  let records = getDataSource();
  records.forEach((item) => {
    delete item.editId;
  });
  for (const r of records) {
    try {
      await r.onEdit(false, false);
    } catch (e) { }
  }
  await reload();
  $message.info('已取消');
}

// 保存
const handleSave = async () => {
  let tableData = getDataSource();
  let orgCode = getForm().getFieldsValue().orgCode;
  let periodCode = getForm().getFieldsValue().periodCode;
  //封装提交的数据
  tableData.forEach((item) => {
    item.periodCode = periodCode;
    item.orgCode = orgCode;
    item.orgName = orgName.value;
    item.templateCode = queryParam.templateCode;
  });
  await updateList({
    datas: tableData,
    orgCode: orgCode,
  });
  await reload();
  startEdit.value = false;
  checkedKeys.value = [];
  startAdd.value = false;
};

</script>

<style scoped lang="less">
@prefix-cls: ~'@{namespace}-depart-manage';

.@{prefix-cls} {
  // update-begin-author:liusq date:20230625 for: [issues/563]暗色主题部分失效
  background: @component-background;
  // update-end-author:liusq date:20230625 for: [issues/563]暗色主题部分失效

  &--box {
    .ant-tabs-nav {
      padding: 0 20px;
    }
  }
}
</style>
